<?php
//用户中心 通过子站点请求设置，获取与移除 当前用户全站的唯一标识符（即session id）。 
require_once 'cfg.php';
require_once 'lib/CnvpClientSSO.class.php';

//获取站点主机后缀(.com, .xxx or .local etc)
$_aHttpHost = explode('.', $_SERVER['HTTP_HOST']);
$_siteSurfix = $_aHttpHost[count($_aHttpHost) - 1];

//设置全站处理需要用到的cookie键名，域名
define('_USER_COOKIE_NAME', 'cookie_forever');              //永久记住用户信息的的cookie键名
define('_SID_NAME', 'sid');                                 //全站sid cookie键名
define('_USER_COOKIE_DOMAIN',  $_SERVER['SERVER_NAME']);    //全域cookie域名

// <editor-fold defaultstate="collapsed" desc="1.参数解析">
$code = trim($_GET['code']);
parse_str(CnvpClientSSO::authcode($code, 'DECODE', _TOKEN_KEY), $get);
if(version_compare(PHP_VERSION,'5.4.0','<')) {
    ini_set('magic_quotes_runtime',0);
    define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()?True:False);
}else
    define('MAGIC_QUOTES_GPC',false);
if (MAGIC_QUOTES_GPC) {
    $get = dstripslashes($get);
}
//验证是否过期
(!isset($get['time'])||time() - $get['time'] > 3600) && exit('Authracation has expiried');
empty($get) && exit('Invalid Request');
$action = $get['action'];
$timestamp = time();
// </editor-fold>
//2. 操作sid
if ($action == 'getSid' && $_GET['time'] == $get['time']) 
// <editor-fold defaultstate="collapsed" desc="2.1获取sid">
{
    !API_GET_SID && exit(API_RETURN_FORBIDDEN);
    // 2.1 获取session id, 如果未获取到但是有cookie永久记住的记录，则对用户进行第一次单点登陆处理

    header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
    $back_url = $get['back_url'];
    $_sessId = isset($_COOKIE[$__SID_NAME]) ? trim($_COOKIE[$__SID_NAME]) : '';

    if (empty($_sessId)) {
        if (isset($_COOKIE[$__USER_COOKIE_NAME][_UC_USER_COOKIE_USERNAME_KEYNAME], $_COOKIE[$__USER_COOKIE_NAME][_UC_USER_COOKIE_PASSWORD_KEYNAME])) {

//3. 根据cookie里的用户名和密码判断用户是否已经登陆。
            $username = CnvpClientSSO::authcode($_COOKIE[$__USER_COOKIE_NAME][_UC_USER_COOKIE_USERNAME_KEYNAME], 'DECODE', _TOKEN_KEY);
            $password = CnvpClientSSO::authcode($_COOKIE[$__USER_COOKIE_NAME][_UC_USER_COOKIE_PASSWORD_KEYNAME], 'DECODE', _TOKEN_KEY);
            $ip = _onlineip();


            $ret = CnvpClientSSO::loginUCenter($username, $password, $ip);
            if ($ret['resultFlag'] > 0) {
                $_sessId = $ret['sessID'];
            }
        }
    }

//
// 2.2 如果成功获取了session id，则将该站注册成已登陆站点
// 说明：除第一个直接登陆站外，其他站的登陆验证必须通过这里获取session id
// //$_sessId登出的时候，并没有注销掉。。。。。。。。。
    if ($_sessId && isset($get['site_flag']) && (0 !== intval($get['site_flag']))) {
        CnvpClientSSO::registerLoggedSite($get['site_flag'], $_sessId);
    }

    $back_url = urldecode($back_url);
    if (false === strstr($back_url, '?')) {
        $back_url .= "?code=" . CnvpClientSSO::authcode("fromuc=true&sessId=" . $_sessId, 'ENCODE', _TOKEN_KEY);
    } else {
        $back_url .= "&code=" . CnvpClientSSO::authcode("fromuc=true&sessId=" . $_sessId, 'ENCODE', _TOKEN_KEY);
    }

    echo "<script>window.location.href='{$back_url}'</script>";
    exit();
}
// </editor-fold>
elseif ($action == 'setSid' && $_GET['time'] == $get['time']) 
// <editor-fold defaultstate="collapsed" desc="2.2设置sid">
{
    /**
     * 3. 设置统一的session id
     */
    !API_SET_SID && exit(API_RETURN_FORBIDDEN);
    
    header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

    $sessId = $get['sid'];
    empty($sessId) && exit(API_SID_EMPTY_ERROR);
    setcookie(_SID_NAME, $sessId, 0, '/', _USER_COOKIE_DOMAIN);
    
    isset( $get['uid']) && setcookie('uid', $get['uid'], 0, '/', _USER_COOKIE_DOMAIN);
    isset( $get['username']) && setcookie('username', $get['username'], 0, '/', _USER_COOKIE_DOMAIN);
    isset( $get['nickname']) && setcookie('nickname', $get['nickname'], 0, '/', _USER_COOKIE_DOMAIN);
    isset( $get['deptid']) && setcookie('deptid', $get['deptid'], 0, '/', _USER_COOKIE_DOMAIN);

    $remember = isset($get['remember']) ? intval($get['remember']) : 0;
    //永久记住登陆账号
    if (1 === $remember) {
        $username = isset($get['username']) ? trim($get['username']) : '';
        $password = isset($get['password']) ? trim($get['password']) : '';
        setcookie(_USER_COOKIE_NAME, '', -1, '/', _USER_COOKIE_DOMAIN);

        setcookie(_USER_COOKIE_NAME, CnvpClientSSO::authcode($username . '|g|' . $password, 'ENCODE', _TOKEN_KEY), $timestamp + 86400 * 365, '/', _USER_COOKIE_DOMAIN);
    }

    exit();
} 
// </editor-fold>
elseif ($action == 'removeSid' && $_GET['time'] == $get['time']) 
// <editor-fold defaultstate="collapsed" desc="2.3清楚sid及永久基础账号的cookie">
    {

    /**
     * 4. 移除统一的session id，和永久记住登陆账号的cookie信息
     */
    !API_SET_SID && exit(API_RETURN_FORBIDDEN);
    header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

    setcookie(_SID_NAME, '', -1, '/');
    setcookie(_USER_COOKIE_NAME, '', -1, '/', _USER_COOKIE_DOMAIN);

    exit();
} 
// </editor-fold>
else {
    exit(API_RETURN_FAILED);
}
// <editor-fold defaultstate="collapsed" desc="公共函数">
/**
 * 数组的递归stripslashes实现
 *
 * @param mixed $string
 * @return mixed
 */
function dstripslashes($string) {
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = dstripslashes($val);
        }
    } else {
        $string = stripslashes($string);
    }
    return $string;
}

/**
 * 获取用户ip
 *
 * @return string
 */
function _onlineip() {
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $onlineip = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $onlineip = $_SERVER['REMOTE_ADDR'];
    }
    return preg_replace("/^([\d\.]+).*/", "\\1", $onlineip);
}
// </editor-fold>

?>